package cn.smxy.user.service.impl;

import cn.smxy.client.CollegeClient;
import cn.smxy.constant.RegexConstant;
import cn.smxy.constant.UserConstant;
import cn.smxy.param.CampusRemoveParam;
import cn.smxy.param.CampusSearchParam;
import cn.smxy.param.CollegeDetailParam;
import cn.smxy.param.UserIdParam;
import cn.smxy.pojo.Campus;
import cn.smxy.pojo.College;
import cn.smxy.pojo.User;
import cn.smxy.user.mapper.CampusMapper;
import cn.smxy.user.mapper.UserMapper;
import cn.smxy.user.service.CampusService;
import cn.smxy.user.service.UserService;
import cn.smxy.user.util.NumberUtil;
import cn.smxy.util.R;
import cn.smxy.vo.CampusVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class CampusServiceImpl implements CampusService {

    @Autowired
    private CampusMapper campusMapper;
    @Autowired
    private CollegeClient collegeClient;
    @Autowired
    private UserService userService;

    /**
     * 校园认证批量删除
     *
     * @param campusRemoveParam
     * @return
     */
    @Override
    public R campusRemoveBatch(CampusRemoveParam campusRemoveParam) {
        String[] campusStrings = campusRemoveParam.getCampusIds().split(",");
        Long[] campusIds = new Long[campusStrings.length];
        for (int i = 0; i < campusStrings.length; i++) {
            campusIds[i] = Long.parseLong(campusStrings[i]);
        }
        String[] userStrings = campusRemoveParam.getUserIds().split(",");
        Long[] userIds = new Long[userStrings.length];
        for (int i = 0; i < userStrings.length; i++) {
            userIds[i] = Long.parseLong(userStrings[i]);
        }
        int rows = campusMapper.deleteBatchIds(Arrays.asList(campusIds));
        if(rows == 0) {
            log.info("CampusServiceImpl.campusRemoveBatch业务结束，结果为:{}","删除失败");
            return R.fail("删除失败");
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("user_role", UserConstant.ROLE_USER);
        updateWrapper.set("college_id",null);
        updateWrapper.in("user_id", userIds);
        boolean update = userService.update(updateWrapper);
        if(!update) {
            log.info("CampusServiceImpl.campusRemoveBatch业务结束，结果为:{}","修改用户权限失败");
            return R.fail("删除失败");
        }
        return R.ok("删除成功");
    }

    /**
     * 分页展示校园认证
     *
     * @param campusSearchParam
     * @return
     */
    @Override
    public R page(CampusSearchParam campusSearchParam) {
        // 条件拆分
        String realName = campusSearchParam.getRealName();
        Long collegeId = campusSearchParam.getCollegeId();
        int currentPage = campusSearchParam.getCurrentPage();
        int pageSize = campusSearchParam.getPageSize();
        // 条件封装
        QueryWrapper<Campus> queryWrapper = new QueryWrapper<>();
        if(realName != null) {
            queryWrapper.like("real_name",realName);
        }
        if(collegeId != null && collegeId != -1) {
            queryWrapper.eq("college_id",collegeId);
        }
        IPage<Campus> page = new Page<>(currentPage,pageSize);
        page = campusMapper.selectPage(page, queryWrapper);
        List<Campus> records = page.getRecords();
        long total = page.getTotal();
        R ok = R.ok("",records,total);
        log.info("CampusServiceImpl.page业务结束，结果为:{}",ok);
        return ok;
    }

    /**
     * 查看校园认证详情
     * 1.条件封装
     * 2.查询并返回
     *
     * @param userIdParam 用户id参数
     * @return
     */
    @Override
    public R view(UserIdParam userIdParam) {
        // 条件封装
        QueryWrapper<Campus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userIdParam.getUserId());
        // 数据库查询
        Campus campus = campusMapper.selectOne(queryWrapper);
        // 获取高校id对应的高校名
        CollegeDetailParam collegeDetailParam = new CollegeDetailParam();
        collegeDetailParam.setCollegeId(campus.getCollegeId());
        R r = collegeClient.detail(collegeDetailParam);
        ObjectMapper objectMapper = new ObjectMapper();
        College college = objectMapper.convertValue(r.getData(), College.class);
        CampusVo campusVo = new CampusVo(campus);
        campusVo.setCollegeName(college.getCollegeName());
        log.info("CampusServiceImpl.view业务结束，结果为:{}",campusVo);
        return R.ok("校园认证信息查询成功",campusVo);
    }

    /**
     * 校园学生认证
     * 1.正则校验姓名是否符合规则
     * 2.调用college服务查询学号校验方法(校验是否存在该学校)
     * 3.校验学号是否符合规则
     * 4.符合规则插入数据库
     * 5.修改user权限，学校名称
     * 6.返回封装结果
     *
     * @param campus 校园实体类
     * @return
     */
    @Override
    public R check(Campus campus) {
        // 正则校验姓名是否符合规则
        Pattern pattern = Pattern.compile(RegexConstant.USER_REAL_NAME);
        Matcher matcher = pattern.matcher(campus.getRealName());
        if(!matcher.matches()) {
            log.info("CampusServiceImpl.check业务结束，结果为:{}","真实姓名错误，认证失败");
            return R.fail("认证信息错误，认证失败");
        }
        // 调用college服务查询学号校验方法
        CollegeDetailParam collegeDetailParam = new CollegeDetailParam();
        collegeDetailParam.setCollegeId(campus.getCollegeId());
        R detail = collegeClient.detail(collegeDetailParam);
        if(R.FAIL_CODE.equals(detail.getCode())) {
            log.info("CampusServiceImpl.check业务结束，结果为:{}","学校不存在，认证失败");
            return R.fail("认证信息错误，认证失败");
        }
        // 校验学号是否符合规则
        // LinKedHashMap处理，利用jackson转成实体类
        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) detail.getData();
        ObjectMapper mapper = new ObjectMapper();
        College college = mapper.convertValue(map,College.class);
        if(!NumberUtil.check(college,campus.getStudentNumber())) {
            log.info("CampusServiceImpl.check业务结束，结果为:{}","学号不符合规则，认证失败");
            return R.fail("认证信息错误，认证失败");
        }
        campus.setCreateTime(System.currentTimeMillis());
        int rows = campusMapper.insert(campus);
        if(rows == 0) {
            log.info("CampusServiceImpl.check业务结束，结果为:{}","数据插入失败");
            return R.fail("认证异常");
        }
        // 修改用户权限，学校id
        User user = userService.getBaseMapper().selectById(campus.getUserId());
        user.setUserRole(UserConstant.ROLE_STUDENT);
        user.setCollegeId(campus.getCollegeId());
        userService.getBaseMapper().updateById(user);
        return R.ok("认证成功");
    }
}
